// pages/dealer/dealerPay.js
var app = getApp()
var isDealer = 0
Page({
  data: {
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    dealer: null,
    hasNoCoupons: true,
    coupons: [],
    youhuijine: 0, //优惠券金额
    curCoupon: null, // 当前选择使用的优惠券
    dealerId: '',
    isValid: 0,
    orderId: '',
    items: [
      {value: 1, name: '微信支付', checked: 'true'},
      {value: 2, name: '对公账号'}
    ],
    payType: 1,
    hideShopPopup: true,
    newStandard: null,
    successPic:'',
    orderId:'',
    showSuccess:false,
    firstChange: true
  },
  goBack(){
    wx.navigateBack();
  },
  showPop(e){
    let stand = e.currentTarget.dataset.stand
    var childs =  this.data.goodsList[0].standard
    childs.forEach( item => {
      item.active = false
    })
    if(stand){
      for (var i = 0; i < childs.length; i++) {
        if( childs[i].Id == stand.Id ){
          childs[i].active = true
        }
      }
    }else{
      childs[0].active = true
    }
    this.data.goodsList[0].standard = childs
    // childs[0].active = true
    this.setData({
      hideShopPopup: false,
      standardPrice: this.data.goodsList[0].standard[0].Price,
      goodsList: this.data.goodsList
    })
  },
  closePopupTap: function () {
    this.setData({
      hideShopPopup: true
    })
  },
  radioChange(e){
    if( e.detail.value == 2 && this.data.firstChange ){
      wx.showModal({
        title: '温馨提示',
        content: '如果您选择对公账号汇款，请在汇款的备注栏注明（经销商姓名或者订单编号后6位数字），以便核对。谢谢',
        showCancel: false
      })
      this.setData({
        firstChange: false
      })
    }
    this.setData({
      payType: e.detail.value
    })
  },

  onShow: function () {
    let that = this
    //显示收货地址标识
    that.initShippingAddress();
    //console.log(this.data.orderType)
    app.get('dealer/get_dealer_by_custid?CustId=' + app.globalData.uid, res => {
      if (res.result) {
        this.setData({
          dealerId: res.result.Id
        })
      }
    })
    app.get('sysconfig/get_sysconfig_by_key?Key=success_pic', res => {
      console.log(res)      
      this.setData({
        successPic: res.result.Desc
      })
    })
    if( wx.getStorageSync('dealerInfo') ) {
      this.setData({
        dealer: wx.getStorageSync('dealerInfo')
      })
    }
  },

  labelItemTap: function (e) {
    var that = this;
    // 取消该分类下的子栏目所有的选中状态
    var childs =  that.data.goodsList[0].standard;
    for (var i = 0; i < childs.length; i++) {
      childs[i].active = false;
    }
    // 设置当前选中状态
    childs[e.currentTarget.dataset.propertyindex].active = true
    that.setData({
      standardPrice: childs[e.currentTarget.dataset.propertyindex].Price
    })
    that.data.goodsList[0].standard = childs
    that.data.goodsList[0].label = childs[e.currentTarget.dataset.propertyindex].Name
    that.data.goodsList[0].number = childs[e.currentTarget.dataset.propertyindex].MinBuy
    that.data.goodsList[0].price = childs[e.currentTarget.dataset.propertyindex].Price
    
    that.data.allGoodsPrice = childs[e.currentTarget.dataset.propertyindex].Price * childs[e.currentTarget.dataset.propertyindex].MinBuy
    this.setData({
      hideShopPopup: true,
      newStandard: childs[e.currentTarget.dataset.propertyindex],
      goodsList: that.data.goodsList,
      allGoodsPrice: that.data.allGoodsPrice
    })
    console.log( that.data.newStandard )
    that.data.newStandard.Num = that.data.newStandard.MinBuy
    let postData = {
      OrderId: that.data.orderId,
      StandardId: that.data.goodsList[0].standardId,
      NewStandard: JSON.stringify(that.data.newStandard)
    }
    app.postForm('order/update_order_detail_standard_by_orderid', postData, res => {
      console.log(res)
      if( res.code == 0 ){
        that.data.goodsList[0].standardId = that.data.newStandard.Id
      }
    })
  },
  onLoad: function (e) {
    //console.log(e)
    var that = this;
    wx.hideShareMenu()
    var shopList = [];
    if (app.globalData.iphone == true) { that.setData({ iphone: 'iphone' }) }
    this.setData({
      orderId: e.orderId
    })
    wx.getStorage({
      key: 'orderDetail',
      success(res) {
        shopList = JSON.parse(res.data);
        let total = 0;
        for (let i in shopList) {
          total += Number(shopList[i].number) * Number(shopList[i].price);
        }
        that.setData({
          goodsList: shopList,
          allGoodsPrice: total,
          allGoodsAndYunPrice: total
        })
        let obj = {
          Name: that.data.goodsList[0].label
        }
        that.setData({
          newStandard: obj
        })
        for (let i = 0; i < that.data.goodsList.length; i++) {
          try {
            if (that.data.goodsList[i].IsDealer == 1) {
              that.setData({
                isValid: 1
              })
              break
            } else {
              that.setData({
                isValid: 0
              })
            }
          } catch (error) {
    
          }
        }
      }
    })

  },


  createOrder: function (e) {
    wx.showLoading(           {
      title: '加载中...',
      mask: true});
    var that = this;
    // var loginToken = app.globalData.token // 用户登录 token
    var remark = ""; // 备注信息
    if (e) {
      remark = e.detail.value.remark; // 备注信息
    }
    if( that.data.payType == 2 ){
      let postData = {
        PayType: that.data.payType,
        OrderId: that.data.orderId
      }
      app.postForm('order/update_order_paytype_by_orderid', postData, res => {
        if( res && res.code == 0 ){
          wx.showToast({
            title: '订单已提交',
            icon: 'success',
            duration: 1000,
            success: () => {
              setTimeout(function () {
                wx.navigateBack({
                  delta: 1 //返回上一级页面
                })
              }, 1000)
            }
          })
        }
      })
    }else{
      let payData = {
        OrderIds: that.data.orderId,
        OpenId: app.globalData.openid,
        Type: 'JSAPI'
      }
      that.setData({
        orderId:that.data.orderId
      })
      app.postForm('order/pay_order_by_orderids', payData, rep => {
        // console.log(rep)
        wx.hideLoading()
        wx.removeStorageSync('orderDetail');
        that.wxPay(rep)
      })
    }
  },
  showSuccessed(){
    wx.hideLoading();
    console.log('/dealer/get_dealer_by_orderid?OrderId='+this.data.orderId);
    app.get('/dealer/get_dealer_by_orderid?OrderId='+this.data.orderId,res=>{
      if(res&&res.code=='0'){
        console.log(res);
        if(res.result.IsValid==1){
          this.setData({
            showSuccess:true
          })
        }
      }
    })
  },
  wxPay(params) {
    console.log(params)
    let that=this;
    wx.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: params.package,
      signType: 'MD5',
      paySign: params.paySign,
      success: function (res) {
        wx.showLoading({
          title: '处理中',
          mask: true,
        })
        setTimeout(that.showSuccessed,3000);
          // wx.showToast({
          //   title: '支付成功',
          //   icon: 'success',
          //   duration: 1000,
          //   success: () => {
          //     setTimeout(function () {
          //       wx.navigateBack({
          //         delta: 1 //返回上一级页面
          //       })
          //     }, 1000)
          //   }
          // })
        
      },
      fail: function (res) {
        wx.showToast({
          title: '已取消支付',
          icon: 'success',
          duration: 1500,
          // success: () => {
          //   setTimeout(function () {
          //     wx.navigateBack({
          //       delta: 1 //返回上一级页面
          //     })
          //   }, 1500)
          // }
        })
      },
      complete: function (res) {
        console.log(res);        
      }
    })
  },
  initShippingAddress: function () {
    var that = this;
    app.get("/user/get_address_by_custid?CustId=" + app.globalData.uid, (res) => {
      console.log(res);

      if (res && res.code == "0") {
        var addr = res.result.find(item => item.IsDefault == 1);
        if (res.result.length > 0) {
          if (addr) {
            addr.District = addr.District == "请选择" ? "" : addr.District;
          } else {
            addr = res.result[0]
            addr.District = addr.District == "请选择" ? "" : addr.District;
          }
          that.setData({
            curAddressData: addr
          });
        } else {
          that.setData({
            curAddressData: null
          })
        }


        console.log(that.data.curAddressData)
      }
    });
   
  },
  processYunfei: function () {
    var that = this;
    var goodsList = this.data.goodsList;
    var goodsJsonStr = "[";
    var isNeedLogistics = 0;
    var allGoodsPrice = 0;

    for (let i = 0; i < goodsList.length; i++) {
      let carShopBean = goodsList[i];
      if (carShopBean.logistics) {
        isNeedLogistics = 1;
      }
      allGoodsPrice += carShopBean.price * carShopBean.number;

      var goodsJsonStrTmp = '';
      if (i > 0) {
        goodsJsonStrTmp = ",";
      }


      let inviter_id = 0;
      let inviter_id_storge = wx.getStorageSync('inviter_id_' + carShopBean.goodsId);
      if (inviter_id_storge) {
        inviter_id = inviter_id_storge;
      }


      goodsJsonStrTmp += '{"goodsId":' + carShopBean.goodsId + ',"number":' + carShopBean.number + ',"propertyChildIds":"' + carShopBean.propertyChildIds + '","logisticsType":0, "inviter_id":' + inviter_id + '}';
      goodsJsonStr += goodsJsonStrTmp;


    }
    goodsJsonStr += "]";
    //console.log(goodsJsonStr);
    that.setData({
      isNeedLogistics: isNeedLogistics,
      goodsJsonStr: goodsJsonStr
    });
    that.createOrder();
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/address-add"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/address/address"
    })
  },
  getMyCoupons: function () {
    var that = this;
  },
  bindChangeCoupon: function (e) {
    const selIndex = e.detail.value[0] - 1;
    if (selIndex == -1) {
      this.setData({
        youhuijine: 0,
        curCoupon: null
      });
      return;
    }
    //console.log("selIndex:" + selIndex);
    this.setData({
      youhuijine: this.data.coupons[selIndex].money,
      curCoupon: this.data.coupons[selIndex]
    });
  }
})